<?php


namespace App\Aspect;


use App\Component\UidBand;
use App\Model\User;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Hyperf\SocketIOServer\SidProvider\SidProviderInterface;
use Hyperf\WebSocketServer\Collector\FdCollector;


/**
 * 切片类，切入socketIo的连接关闭事件，关闭前解绑uid
 * Class SocketCloseAspect
 * @package App\Aspect
 */
class SocketCloseAspect extends AbstractAspect
{
    public $classes = [
        'Hyperf\WebSocketServer\Server::onClose'
    ];


    public function process(ProceedingJoinPoint $proceedingJoinPoint)
    {
        //获取切入方法的参数
        $arg = $proceedingJoinPoint->getArguments();
        //通过容器获取到SidProvider对象，获取sid
        $container = \Hyperf\Utils\ApplicationContext::getContainer();
        $SidProvider = $container->get(SidProviderInterface::class);
        $sid = $SidProvider->getSid($arg[1]);
        //解绑uid
        $uid = UidBand::getInstance()->getUidByFd($sid);
        UidBand::getInstance()->unBindUid($sid,$uid);
        //更新用户状态为下线
        $user = User::query()->find($uid);
        if($user){
            $user->status = 'offline';
            $user->save();
        }
        //推送下线消息


        $result = $proceedingJoinPoint->process();
        return $result;
    }
}